package com.bwhx.eruler.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bwhx.eruler.bean.Staff;



public abstract class BaseController {
	
	@Autowired
	private  HttpServletRequest request;
	
	final String CONSTANT_STATUS = "status";
	final String CONSTANT_MSG = "msg";
	final String CONSTANT_WHY = "why";
	
	public Log log = LogFactory.getLog(this.getClass());
	
	@InitBinder
	//此方法用于日期的转换，如果未加，当页面日期格式转换错误，将报400错误，实际是因为此方法
	public void initBinder(WebDataBinder binder) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(true);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	@ExceptionHandler(Exception.class)  
	@ResponseBody
    public Map<String, String> exceptionHandler(Exception exception) {  
		
		
		log.error(this.getClass().getName(),exception);
 		exception.printStackTrace();
		Map<String, String> map = new HashMap<String, String>();
		map.put("status", "0");
		map.put("meg", "失败");
		map.put("msg", "失败！");
        return map;  
    }  
	
	public Staff getSessionStaff(){
		Staff staff = (Staff) request.getSession().getAttribute("staff");
		return staff;
		
	}
	
	public String getTrace(Throwable t){
		
		StringWriter stringWriter= new StringWriter();
		PrintWriter writer= new PrintWriter(stringWriter);
		t.printStackTrace(writer);
		StringBuffer buffer= stringWriter.getBuffer();
		return buffer.toString();
	}

}
